import {Notification, MessageBox} from 'element-ui';
// import store from '@/store'
// import vueThat from "@/main";

export default {
  getParamQueryString (key, url) {
    let subStr = key + '=';
    url = url || window.location.href;
    if (url.indexOf(subStr) !== -1) {
      let arr = url.split(subStr)
      let sub1 = arr[1]
      if (sub1.indexOf('&') !== -1) {
        let arr2 = sub1.split('&')
        let sub2 = arr2[0]
        return sub2
      } else {
        return sub1
      }
    }
    return ''
  },
  /**
   * @about 根据url判断是内部跳转还是跳出页面，并进行跳转
   * @param
   *      url:{链接(http://www.baidu.com),内部跳转({name:'test'})},
   *      $router:路由
   * @return 无返回值，进行页面跳转
   * @author bob
   */
  go(url, $router, replace) {
    if (/^javas/.test(url) || !url) {
      return;
    }
    if (url.showError) {
      Notification.error({
        title: '错误',
        message: url.showError
      });
      return;
    }
    const useRouter = typeof url === 'object' || ($router && typeof url === 'string' && !/http/.test(url));
    if (useRouter) {
      if (replace || url.replace) {
        $router.replace(url);
      } else {
        $router.push(url);
      }

    } else {
      window.open(url, '_blank');
    }
  },
  back($router, step) {
    let stp = step ? -step : -1;
    $router.go(stp);
  },
  /**
   * @about 打开页面(如果在compass集成下，打开新的tab标签)
   * @param
   *      param:{
   *             "url":"/app/demo",//请求url，必填
   *             "text":"详情页面",//compass下tab名称
   *             "mid":"12323123",//compass的tab唯一值，一个tab一个值，如果是相同的mid，打开的是用一个tab
   *             "param":{},//请求参数，选填，默认{}
   *             "router":this.$router,//router对象，如果不是compass下通过go调用使用
   *           }
   * @return 无
   * @author wanglu
   */
  openPage(param) {
    let that = this;
    var _p = {
      url: '',
      text: '新开页面',
      mid: (new Date()).getTime(),
      param: {},
      router: null
    }
    _p = Object.assign(_p, param);
    if (_p.router == null) {
      return;
    }
    try {
      // if (window.parent && window != window.parent) {
      if (window.parent && window.self != window.top && window.parent.long) {
        var url_param = '';
        for (var key in _p.param) {
          if (_p.param[key]) {
            url_param += key + '=' + _p.param[key] + '&';
          }
        }
        if (url_param) {
          _p.url = window.location.origin +  _p.url + "?" + url_param.substr(0, url_param.length - 1);
        } else {
          _p.url = window.location.origin +  _p.url;
        }
        window.parent.long.open_page(_p.mid, _p.text, _p.url);
      } else {
        that.go({
          path: _p.url,
          query: _p.param
        }, _p.router);
      }
    } catch (e) {
      console.log("openPage异常:" + e);
      that.go({
        path: _p.url,
        query: _p.param
      }, _p.router);
    }
  },
  // TODO:打开新tags标签
  openPagefix(param) {
    let that = this;
    var _p = {
      url: '',
      text: '新开页面',
      mid: (new Date()).getTime(),
      param: {},
      router: null
    }
    _p = Object.assign(_p, param);
    if (_p.router == null) {
      return;
    }
    try {
      if (window.parent && window.parent.long) {
        var url_param = '';
        for (var key in _p.param) {
          if (_p.param[key]) {
            url_param += key + '=' + _p.param[key] + '&';
          }
        }
        if (url_param) {
          _p.url = window.location.origin +  _p.url + "?" + url_param.substr(0, url_param.length - 1);
        } else {
          _p.url = window.location.origin +  _p.url;
        }
        window.parent.long.open_page(_p.mid, _p.text, _p.url);
      } else {
        that.go({
          path: _p.url,
          query: _p.param
        }, _p.router);
      }
    } catch (e) {
      console.log("openPage异常:" + e);
      that.go({
        path: _p.url,
        query: _p.param
      }, _p.router);
    }
  },
  // TODO:打开新页面（新窗口、当前页打开）
  open(url, newWindow) {
    if (url.indexOf('?') >= 0)
      url += "&_t=" + (new Date()).getTime();
    else
      url += "?_t=" + (new Date()).getTime();
    if (newWindow) {
      window.open(url);
    } else {
      window.location.href = url;
    }
  },
  // TODO:打开新tags标签（子ifarme）
  // open_page(id, text, url) {
  //   let that = this;
  //   if (url) {
  //     let item = {
  //       fullName: text,
  //       urlAddress: url,
  //     }
  //     if (url == '/login') {
  //       that.open_login();
  //       return;
  //     }
  //     item.componentId = (store.state.menus.currMenu || {}).id;
  //     item.tag__open_time = (new Date()).getTime();
  //     store.state.tagsView.curr_tagView = item;
  //     store.dispatch('tagsView/addView', item);
  //   }
  // },
  open_login(flag, type, msg, opts) { // 是否直接退出、是否确认退出、确认提示
    // localStorage.clear();
    console.log('++++++')
    // if (window.parent && window.self != window.top) {
    //   try {
    //     window.parent.long.open_login(flag, type, msg, opts);
    //   } catch (error) {
    //     window.top.long.open_login(flag, type, msg, opts);
    //   }
    // } else {
    //   if (flag) {
    //     location.replace('/login'+(window.auth_tid ? ('?tid=' + window.auth_tid) : ''));
    //   } else {
    //     MessageBox[(type||'alert')](msg || '登录状态已过期，请重新登录', '系统提示', Object.assign({
    //       showClose: false,
    //       confirmButtonText: '重新登录',
    //       type: 'warning',
    //       beforeClose: (action, instance, done) => {
    //         if (action === 'confirm') {
    //           // 'confirm', 'cancel'或'close'
    //           opts && opts.cancelButtonText ? store.dispatch('LogOut') : store.dispatch('FedLogOut', true);
    //         }
    //         done();
    //       }
    //     }, opts || {})).then(() => {
    //       // opts && opts.cancelButtonText ? store.dispatch('LogOut') : store.dispatch('FedLogOut', true);
    //     }).catch(() => {});
    //   } 
    // }
  },

  // success warning error
  // compass内提示信息展示
  message(message, type) {
    if (longp && longp.layer) {
      var data = {
        time: 5000,
        icon: 1,
        anim: 6,
        offset: '30px',
        closeBtn: false,
        skin: 'demo-class'
      };
      if (type == 'warning') {
        data.icon = 7;
      } else if (type == 'error') {
        data.icon = 2;
      } else {
        data.anim = 5
      }
      // 7 warning, 1 success, 2 error
      longp.layer.msg(message, data);
    } else {
      Notification({
        title: '提示',
        message: message,
        type: type || 'success'
      });
    }
  },
  /**
   * @about 操作sessionStorage
   * @param 无
   * @return 无
   * @author bob
   */
  setSession(name, value) {
    if (typeof value == "object") {
      value = JSON.stringify(value);
    }
    sessionStorage.setItem(name, value);
  },
  getSession(name) {
    return sessionStorage.getItem(name);
  },
  delSession(name) {
    if (sessionStorage.getItem(name)) {
      sessionStorage.removeItem(name);
    }
  },

  /**
   * @about 格式化时间
   * @param
   *      date:{number或date}毫秒时间，必填
   *      fmt:{string}需要生成的时间格式，选填 默认  MM-dd hh:mm
   * @return string   格式化时间字符串
   * @author bob
   */
  formatTime(date, format) {
    if (typeof date == "number") {
      date = new Date(date);
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
      };
      var fmt = format || "yyyy-MM-dd hh:mm:ss";
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    } else {
      return date;
    }
  },
  formatPrice(s) {
    var n = 2;
    s = s / 100 * 1 + "";
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
    var t = "";
    for (var i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
  },

  /**
   * @about 包含loading的显隐
   * @param
   *      obj:{
   *             "url":"/app/demo",//请求url，必填
   *             "dataType":"json",//数据格式，选填，默认json
   *             "type":"POST",//请求类型，选填，默认POST
   *             "data":{},//请求参数，选填，默认{}
   *             "success":function(){},//成功回调，选填，默认function(){}
   *             "error":function(){},//error回调，选填，默认function(){}
   *             "async": true,//是否异步，选填，默认true
   *             "message": '拼命加载中',//请求时的文字，选填，默认  拼命加载中
   *             "stringify": 提交数据是否需要stringify，默认不stringify
   *           }
   * @return 无
   * @author bob
   */
  rules: {
    mobile: [{
      required: true,
      message: '请输入手机号',
      trigger: 'blur'
    }, {
      validator: (rule, value, callback) => {
        if (!/^1\d{10}$/.test(value)) {
          callback(new Error('手机号输入错误'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    vcode: [{
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }],
    epy: [{
      required: true,
      message: '不能为空',
      trigger: 'blur'
    }],
    noEmpty: [{
      required: true,
      message: '不能为空',
      trigger: 'blur'
    }, {
      validator: (rule, value, callback) => {
        if (value.indexOf(" ") > -1) {
          callback(new Error('不能包含空格'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    oldPassword: [{
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    }],
    password: [{
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }, {
      min: 6,
      max: 20,
      message: '请输入6-20位数字、字母或常用符号',
      trigger: 'blur'
    }, {
      validator: (rule, value, callback) => {
        if (value.indexOf(" ") > -1) {
          callback(new Error('不能包含空格'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    number: [{
      required: true,
      message: '不能为空',
      trigger: 'blur'
    }, {
      validator: (rule, value, callback) => {
        if (!/^\d+$/.test(value)) {
          callback(new Error('必须为数值类型'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    percent: [{
      validator: (rule, value, callback) => {
        if (/^(0|0.0|0.00)$/.test(value)) {
          callback(new Error('百分比不能为0'));
        } else if (Math.ceil(value) > 100) {
          callback(new Error('百分比只能输入0-100的数值'));
        } else if (!/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/.test(value)) {
          callback(new Error('百分比最多输入两位小数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    money: [{
      validator: (rule, value, callback) => {
        if (/^(0|0.0|0.00)$/.test(value)) {
          callback(new Error('金额不能为0'));
        } else if (!/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/.test(value)) {
          callback(new Error('金额格式有误且最多输入两位小数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    money1: [{
      validator: (rule, value, callback) => {
        if (value == '') {
          callback();
        } else if (/^(0|0.0|0.00)$/.test(value)) {
          callback(new Error('金额不能为0'));
        } else if (!/^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/.test(value)) {
          callback(new Error('金额格式有误且最多输入两位小数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    http: [{
      validator: (rule, value, callback) => {
        if (!/^(http:\/\/|https:\/\/)/.test(value)) {
          callback(new Error('网址必须http://或https://开头'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }],
    selectMore: [{
      validator: (rule, value, callback) => {
        if (value.length == 0) {
          callback(new Error('请选择'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }]
  },
  scrollTo(x, y) {
    try {
      if (window.parent && window.parent.long) {
        window.parent.scrollTo(x, y)
      } else {
        scrollTo(x, y)
      }
    } catch (e) {
      console.log('top:' + e)
    }
  },
  isEmpty(data) {
    if(data === null || data === '' || data === undefined) {
      return true;
    }
    return false;
  },
  formatDate(date, fmt) {
    //格式化日期插件中的返回值
    if (date == undefined || date == '') return;
    date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
    var obj = {
      'y': date.getFullYear(),
      'M': date.getMonth() + 1,
      'd': date.getDate(),
      'H': date.getHours(),
      'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12,
      'm': date.getMinutes(),
      's': date.getSeconds(),
      'S': date.getMilliseconds()
    };
    for (var i in obj) {
      fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
        var val = obj[i] + '';
        for (var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
        return m.length == 1 ? val : val.substring(val.length - m.length);
      });
    }
    return fmt;
  },
  // 根据指定对象返回总数据中指定结果
  ObjectFormate(obj,data) {
    let newObj = {};
    newObj = Object.assign(newObj,obj);
    for(let i in newObj) {
      if(data[i] !== '' || data[i] != null || data[i] && data[i].length > 0) {
        newObj[i] = data[i]
      }
    } 
    return newObj;
  }
}
